import {query} from '../services/outlay';
import {parse} from 'qs';
import {getCurrentMonth} from '../utils/tools';
import * as global from '../global';

const namespace = 'outlay';
export default {
  namespace,
  state: {data:[],loading:true},
  subscriptions:
  {
    setup({ dispatch, history })
    {
      history.listen(location =>
      {
        if (location.pathname === '/'+namespace)
        {
          let month = getCurrentMonth();
          dispatch({
            type: 'query',
            payload: {
              auth_user:'',
              wid: global.appdata.wid,
              period: month
            }
          });
        }
      });
    }
  },

  effects:
  {
    *query({ payload }, { call, put })
    {
      yield put({type:'showLoading'});
      const { data } = yield call(query, parse(payload));
      if(data.result == 'success')
      {
        data.detail.sort((a,b)=>{
          return b.value-a.value;
        });
        yield put({
          type: 'querySuccess',
          payload: {data}
        });
      }
    }
  },

  reducers: {
    querySuccess(state, action)
    {
      return { ...state, ...action.payload,loading:false};
    },
    hideLoading(state)
    {
      return {...state,loading:false};
    },
    showLoading(state)
    {
      return {...state,loading:true};
    }
  }
}